<template>
  <div class="forum-detail">
    <el-card class="post-card">
      <h2 class="post-title">{{ postDetail.title }}</h2>
      <div class="post-meta">
<!--        <span>作者：{{ postDetail.userName }}</span>-->
        <span>发布时间：{{ postDetail.createTime }}</span>
      </div>
      <div class="post-content" v-html="postDetail.content"></div>
    </el-card>

    <el-card class="comment-section">
      <template #header>
        <div class="comment-header">
          <h3>评论（{{ commentList.length }}）</h3>
          <el-button type="primary" @click="showCommentDialog = true">
            发表评论
          </el-button>
        </div>
      </template>

      <div class="comment-list">
        <div v-for="comment in commentList" :key="comment.id" class="comment-item">
          <el-avatar :size="32" :src="comment.avatar" />
          <div class="comment-content">
            <div class="comment-meta">
              <span class="username">{{ comment.userName }}</span>
              <span class="time">{{ comment.createTime }}</span>
            </div>
            <p class="comment-text">{{ comment.content }}</p>
          </div>
        </div>
      </div>
    </el-card>

    <el-dialog v-model="showCommentDialog" title="发表评论" width="600px">
      <el-form :model="commentForm" :rules="commentRules" ref="commentFormRef">
        <el-form-item prop="content">
          <el-input
            v-model="commentForm.content"
            type="textarea"
            :rows="4"
            placeholder="请输入评论内容（200字以内）"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCommentDialog = false">取消</el-button>
        <el-button type="primary" @click="submitComment">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { faker } from '@faker-js/faker'
import {addPostReply, getPostOne, selectPostReplyList} from "@/api/post.js";
import {getUser} from "@/store/userStore.js";

const route = useRoute()
const postId = route.params.id

const postDetail = ref({})
const commentList = ref([])
const showCommentDialog = ref(false)
const commentForm = ref({ content: '' })
const commentFormRef = ref(null)

const commentRules = {
  content: [
    { required: true, message: '评论内容不能为空', trigger: 'blur' },
    { max: 200, message: '评论内容不能超过200字', trigger: 'blur' }
  ]
}

const generateMockDetail = () => ({
  post: {
    id: faker.string.uuid(),
    title: faker.lorem.words(8),
    content: faker.lorem.paragraphs(3),
    userName: faker.person.fullName(),
    createTime: faker.date.recent().toLocaleString(),
    viewCount: faker.number.int({ min: 100, max: 1000 })
  },
  comments: Array.from({ length: faker.number.int({ min: 5, max: 10 }) }, () => ({
    id: faker.string.uuid(),
    avatar: faker.image.avatar(),
    userName: faker.person.fullName(),
    content: faker.lorem.paragraph(),
    createTime: faker.date.recent().toLocaleString()
  }))
})

const fetchPostDetail = async () => {
  // if (import.meta.env.MODE === 'development') {
  //   const mockData = generateMockDetail()
  //   postDetail.value = mockData.post
  //   commentList.value = mockData.comments
  //   return
  // }
  try {
    const res = await getPostOne(postId)
    postDetail.value = res.data
    const comments = await selectPostReplyList(postId)
    commentList.value = comments.data
  } catch (error) {
    console.error('获取帖子详情失败:', error)
  }
}

const submitComment = async () => {
  try {
    await commentFormRef.value.validate()
    await addPostReply({
      userId: getUser().userInfo.id,
      postId: postId,
      content: commentForm.value.content
    })
    showCommentDialog.value = false
    commentForm.value.content = ''
    await fetchPostDetail()
  } catch (error) {
    console.error('提交评论失败:', error)
  }
}

onMounted(() => {
  fetchPostDetail()
})
</script>

<style scoped>
.forum-detail {
  padding: 20px;
}
.post-card {
  margin-bottom: 20px;
}
.post-title {
  margin-bottom: 15px;
}
.post-meta {
  display: flex;
  gap: 20px;
  color: #666;
  margin-bottom: 15px;
}
.post-content {
  line-height: 1.6;
}
.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.comment-item {
  display: flex;
  gap: 15px;
  padding: 15px 0;
  border-bottom: 1px solid #eee;
}
.comment-content {
  flex: 1;
}
.comment-meta {
  display: flex;
  justify-content: space-between;
  color: #666;
  margin-bottom: 5px;
}
.comment-text {
  margin: 0;
}
</style>
